package com.tbit.uqbike.client.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.paypal.orders.Capture;
import com.tbit.uqbike.client.constant.DepositStateConstant;
import com.tbit.uqbike.client.constant.PayPalCheckoutConstant;
import com.tbit.uqbike.client.constant.RechargeConstant;
import com.tbit.uqbike.client.constant.ResponseCode;
import com.tbit.uqbike.client.dao.core.PayDetailDao;
import com.tbit.uqbike.client.dao.core.PayPalConfigDao;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.*;
import com.tbit.uqbike.client.pojo.payPal.PayDetail;
import com.tbit.uqbike.client.pojo.payPal.PayPalConfig;
import com.tbit.uqbike.client.pojo.payPal.PayPalEntity;
import com.tbit.uqbike.client.remote.paypal.CaptureOrder;
import com.tbit.uqbike.client.remote.paypal.CreateOrder;
import com.tbit.uqbike.client.remote.paypal.RefundOrder;
import com.tbit.uqbike.client.service.*;
import com.tbit.uqbike.client.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: chen
 * @Description: payPal支付
 * @Date: 创建于 14:11 2020/1/10
 */
@Service("payPalService")
@Slf4j
public class PayPalServiceImpl implements PayPalService {


    @Autowired
    private PayPalConfigDao payPalConfigDao;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserService userService;
    @Autowired
    private RechargeService rechargeService;
    @Autowired
    private WeixinDepositLogService weixinDepositLogService;
    @Autowired
    private PayDetailDao payDetailDao;
    @Autowired
    private RideLogService rideLogService;

    @Autowired
    private MemberLogService memberLogService;
    @Autowired
    private MemberFeeService memberFeeService;
    @Autowired
    private RideCardUserService rideCardUserService;
    @Autowired
    private AdAccountDepositService adAccountDepositService;
    @Autowired
    private AgentDepositVipService agentDepositVipService;
    @Autowired
    private RideCardService rideCardService;
    @Autowired
    private WeixinPayService weixinPayService;
    @Autowired
    private VipCardService vipCardService;
    @Autowired
    private VipCardLogService vipCardLogService;
    @Autowired
    private RedisService redisService;

    @Override
    public Map<String, Object> getOrder(PayPalEntity payPalEntity, Integer adAccountId) {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> data = new HashMap<String, Object>();
        String orderNO = WeixinPayUtil.getNonceStr(payPalEntity.getDeposit());
        //基础校验
        baseValid(payPalEntity, data, orderNO);
        //创建订单
        inserOrder(payPalEntity, data, orderNO);
        //返回订单号、clientid、支付模式
        map.put(ResponseCode.RET, ResponseCode.SUCC);
        map.put(ResponseCode.DATA, data);
        return map;
    }

    @Override
    public String callBack(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = RequestToMapUtil.getParameterMap(request);
        log.info(map.toString());
        String outTradeNo = (String) map.get("invoice");
        String paymentStatus = (String) map.get("payment_status");
        String amount = (String) map.get("mc_gross");
        String currency = (String) map.get("mc_currency");
        String paymentId = (String) map.get("txn_id");
        String parentPaymentId = (String) map.get("parent_txn_id");
        log.info("商家订单号 = {}" + outTradeNo);
        log.info("订单状态 = {}" + paymentStatus);
        log.info("金额 = {}" + amount);
        log.info("币种 = {}" + currency);
        log.info("流水号 = {}" + paymentId);
        log.info("父流水号 = {}" + parentPaymentId);

    /*if (!receiverEmail.equals((String) map.get("receiver_email"))) {
      log.info("FAIL = 商户id错误, outTradeNo = {}"+ outTradeNo);
      return "failure";
    }*/
        if ("completed".equalsIgnoreCase(paymentStatus)) {
            Recharge recharge = rechargeService.getByOrderNO(outTradeNo);
            if (recharge != null) {
                User user = userService.getByUserId(recharge.getUserId());
                updateOrderAndBing(recharge, user, paymentId);
            }
            log.info("支付成功,状态为=COMPLETED");
            return PayPalCheckoutConstant.SUCCESS;
        }
        if ("Refunded".equals(paymentStatus)) {
            //进行数据库操作
            //
            //
            log.info("退款成功");
            return PayPalCheckoutConstant.SUCCESS;
        }
        if ("Pending".equals(paymentStatus) && StringUtils.isEmpty(parentPaymentId)) {
            String pendingReason = String.valueOf(map.get("pending_reason"));
            //进行数据库操作
            //
            //
            log.info("订单支付成功,状态为=PENDING，产生此状态的原因是 {}" + pendingReason);
            return PayPalCheckoutConstant.SUCCESS;
        }
        if (StringUtils.isEmpty(parentPaymentId)) {
            if (PayPalCheckoutConstant.PAYMENT_STATUS_REVERSED.equals(paymentStatus)
                    || PayPalCheckoutConstant.PAYMENT_STATUS_CANCELED_REVERSAL.equals(paymentStatus)
                    || PayPalCheckoutConstant.PAYMENT_STATUS_DENIED.equals(paymentStatus)) {
                String reasonCode = String.valueOf(map.get("reason_code"));
                //进行数据库操作(状态修改)
                //
                //
                log.info(String.format("订单异常,请尽快查看处理，状态为=%s，产生此状态的原因是 %s ", paymentStatus, reasonCode));
                return PayPalCheckoutConstant.SUCCESS;
            }
            if (PayPalCheckoutConstant.PAYMENT_STATUS_EXPIRED.equals(paymentStatus)
                    || PayPalCheckoutConstant.PAYMENT_STATUS_CREATED.equals(paymentStatus)
                    || PayPalCheckoutConstant.PAYMENT_STATUS_FAILED.equals(paymentStatus)
                    || PayPalCheckoutConstant.PAYMENT_STATUS_PROCESSED.equals(paymentStatus)
                    || PayPalCheckoutConstant.PAYMENT_STATUS_VOIDED.equals(paymentStatus)) {
                //进行数据库操作(状态修改)
                //
                //
                log.info("其他订单状态,订单异常,请尽快查看处理， 状态={}" + paymentStatus);
                return PayPalCheckoutConstant.SUCCESS;
            }
        }
        return PayPalCheckoutConstant.FAILURE;
    /*String paymentStatus=request.getParameter("payment_status");//支付状态  Completed:支付完成；Refunded：退款
    //退款回调直接终止
    if(StringUtils.isNotBlank(paymentStatus) && "refunded".equals(paymentStatus.toLowerCase()))
    {
      return;
    }

    String orderNo=request.getParameter("custom");//订单号
    log.info("orderNO="+orderNo);
    //1.查询订单
    Recharge recharge = rechargeService.getByOrderNO(orderNo);
    if(recharge==null){
      log.error("订单不存在");
      OutputUtil.renderHtml(request, response, "fail");
    }
    //2.品牌（收款方）支付配置查询
    User user=userService.getByUserId(recharge.getUserId());
    if(user==null){
      log.error("用户不存在");
      OutputUtil.renderHtml(request, response, "fail");
    }
    checkPayPalConfig(user);
    if(recharge.getMoney()==null){
      log.error("订单["+orderNo+"]金额为空");
      return;
    }
    if(StringUtils.isBlank(request.getParameter("payment_gross"))){
      log.error("订单["+orderNo+"]支付金额为空");
      return;
    }
    //3.验证支付有效性
    String mcMoney=request.getParameter("mc_gross");//TODO 待确认-支付总额？
    Double money=Double.parseDouble(request.getParameter("payment_gross"));//支付总额
    log.info("mc_gross:["+mcMoney+"],payment_gross:["+money+"]");
    //调用paypal接口查询订单详情校验支付结果有效性
    if(money.doubleValue()<0) {
      money=-money.doubleValue();
    }
    if(recharge.getMoney().doubleValue()/100!=money.doubleValue()) {
      log.error("paypal订单金额与支付金额不一致,订单号="+orderNo+",订单金额="+recharge.getMoney()/100+"美元,支付金额="+money+"美元");
      return;
    }
    log.info("----------------------");
    //修改订单状态
    Integer state=updateOrder(request,recharge,user,"paypal");
    log.info("state==============="+state);
    insertPayDetail(request,state);*/
    }

    //增加支付详细信息
    private void insertPayDetail(HttpServletRequest request, Integer state) {
        Map<String, String> allParams = CommonUtil.getParamsMap(request);
        String orderNo = allParams.get("custom");
        synchronized (orderNo) {
            String detail = JSONObject.toJSONString(allParams);
            PayDetail pd = payDetailDao.getByOrderNo(orderNo);
            boolean isInsert = false;
            if (pd == null) {
                pd = new PayDetail();
                isInsert = true;
            }
            pd.setOrderNo(allParams.get("custom"));
            pd.setPayerId(allParams.get("payer_id"));

            pd.setPaymentDate(allParams.get("payment_date"));
            pd.setState(state);
            pd.setTransNo(allParams.get("txn_id"));
            pd.setRemark("paypal回调状态值：" + CommonUtil.getStateDes(state, null));
            pd.setDetail(CommonUtil.subStrByLen(detail, 255));
            double money = 0;
            if (allParams.get("payment_gross") != null) {
                money = Double.parseDouble(allParams.get("payment_gross"));
                if (money < 0) {
                    money = -money;
                }
            }
            pd.setMoney(money);
            pd.setPaypalState(allParams.get("payment_status") + ";" + allParams.get("payment_type") + ";" + allParams.get("payer_status"));
            if (isInsert) {
                payDetailDao.insert(pd);
            } else {
                payDetailDao.update(pd);
            }
            log.info("paypal回调日志[" + orderNo + "]：" + detail);
        }

    }

    @Override
    public Map<String, Object> callBackFromApp(String token, String orderNO, Double money, String orderId, Integer accountId) {
        Map<String, Object> map = new HashMap<String, Object>();
        User user = tokenService.getUser(token);
        if (user == null) {
            throw new BaseException("-20005", "");
        }

        Recharge recharge = rechargeService.getByOrderNO(orderNO);
        if (recharge == null) {
            throw new BaseException("-101", "");
        }
        PayPalConfig config = checkPayPalConfig(user);
        if (config == null) {
            throw new BaseException("-2011", "该品牌paypal未配置");
        }
        /**费用扣除*/
    /*BraintreeGateway gateway = getBrainTree(user.getAccountId());
    String payId = PaypalUtils.cash(gateway,money,orderId,orderNO);*/
        CaptureOrder captureOrder = new CaptureOrder();
        Capture capture = null;
        try {
            capture = captureOrder.captureOrder(config.getMode(), config.getClientId(), config.getClientSecret(), orderId);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

        if (capture != null) {
            if (!capture.status().equalsIgnoreCase("COMPLETED")) {
                throw new BaseException("-3061", "操作失败，请重试");
            }
            /**手动查询订单信息*/
            Boolean result = captureOrder.capturesGet(config.getMode(), config.getClientId(), config.getClientSecret(), capture.id());
            if (!result) {
                throw new BaseException("-3061", "操作失败，请重试");
            }
            /**操作成功,扣款*/
            updateOrderAndBing(recharge, user, orderId);
        } else {
            throw new BaseException("-3061", "操作失败，请重试");
        }

    /*if(payId!=null){
      Recharge rechargeNew=new Recharge();
      rechargeNew.setOrderNO(orderNO);
      rechargeNew.setState(1);
      rechargeNew.setPayTime(DateTimeUtil.getNowTime());
      rechargeService.update(rechargeNew);
      //weixinPayService.pay(recharge,"",payId);
    }else{
      throw new BaseException("-3061","操作失败，请重试");
    }*/
        //Map<String, Object> data=new HashMap<String, Object>();
        map.put(ResponseCode.RET, ResponseCode.SUCC);
        //map.put(ResponseCode.DATA, data);
        return map;
    }

    @Override
    public void updateOrderAndBing(Recharge recharge, User user, String transId) {
        synchronized (recharge.getOrderNO()) {
            Recharge rechargeDB = rechargeService.getByOrderNO(recharge.getOrderNO());
      /*if(rechargeDB.getState()==1 || recharge.getState()!=1) {
        return;
      }*/
            if (rechargeDB.getState() == 1) {
                return;
            }
            String time = DateTimeUtil.getNowTime();
            recharge.setState(1);
            recharge.setPayTime(time);
            rechargeService.update(recharge);
            /**支付逻辑处理*/
            weixinPayService.pay(recharge, recharge.getOrderNO(), transId, time, null);
        }
    }

    @Override
    public Map<String, Object> createOrder_memberFee(PayPalEntity payPalEntity, Integer memberFeeId, Integer adAccountId) {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> data = new HashMap<String, Object>();
        /** 查询会员费率 */
        MemberFee memberFee = memberFeeService.findById(memberFeeId);
        if (memberFee == null) {
            throw new BaseException("-130005", "未找到对应会员信息");
        }
        User user = tokenService.getUser(payPalEntity.getToken());

        User userDB = userService.getByUserId(user.getUserId());
        AdAccountDeposit adAccountDeposit = adAccountDepositService.getByAccountId(adAccountId);
        if (adAccountDeposit != null && ((userDB.getDepositState() == DepositStateConstant.DEPOSIT_STATE_PAY
                && userDB.getDepositMoney() >= adAccountDeposit.getDeposit()) || userDB.getDepositState() == DepositStateConstant.DEPOSIT_STATE_SCORE)) {
            throw new BaseException("-3009", "已交押金");
        }

        payPalEntity.setMoney(memberFee.getMoney());
        payPalEntity.setUserId(user.getUserId());
        //基础校验
        //baseValid(payPalEntity,data);
    /*String token = getToken(user.getAccountId());
    data.put("accessToken", token);*/
        String orderNO = "UQBIKEDM" + DateTimeUtil.getDaformatyyyyMMddHHmmss(new Date()) + TenpayUtil.buildRandom(6);
        //基础校验
        baseValid(payPalEntity, data, orderNO);
        //创建订单
        inserOrder(payPalEntity, data, orderNO);
        /**免押会员开通记录*/
        MemberLog memberLog = new MemberLog();
        memberLog.setUserId(payPalEntity.getUserId());
        memberLog.setAccountId(payPalEntity.getAdAccountId());
        memberLog.setMoney(memberFee.getMoney());
        memberLog.setBuyTime(DateTimeUtil.getNowTime());
        memberLog.setMemberFeeId(memberFeeId);
        memberLog.setOrderNO(data.get("orderNo").toString());
        memberLog.setMemberState(0);
        memberLog.setRemark("用户国际paypal支付");
        memberLogService.insert(memberLog);
        //返回订单号、clientid、支付模式
        map.put(ResponseCode.RET, ResponseCode.SUCC);
        map.put(ResponseCode.DATA, data);
        return map;
    }

    @Override
    public Map<String, Object> createOrder_rideCard(PayPalEntity payPalEntity, Integer rideCardId, Integer adAccountId) {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> data = new HashMap<String, Object>();

        User user = tokenService.getUser(payPalEntity.getToken());
        /**查询骑行卡信息*/
        RideCard rideCard = rideCardService.getById(rideCardId);
        if (rideCard == null) {
            throw new BaseException("-120002", "骑行卡不存在");
        }

        /**删除未支付的订单*/
        rideCardUserService.delNotPay(user.getUserId());

        /**查询是否有生效中的骑行卡*/
        List<RideCardUser> rideCardUsers = rideCardUserService.getRideVaildCard(user, rideCard.getAccountId(), rideCard.getFeeId());

        if (rideCardUsers.size() > 0) {
            throw new BaseException("-120003", "购买失败,ResponseCode.printException(map, e,request)中的骑行卡");
        }
        payPalEntity.setUserId(user.getUserId());
        payPalEntity.setMoney(rideCard.getMoney());

        String orderNO = "UQBIKERC" + DateTimeUtil.getDaformatyyyyMMddHHmmss(new Date()) + TenpayUtil.buildRandom(6);
        //基础校验
        baseValid(payPalEntity, data, orderNO);
        //创建订单
        inserOrder(payPalEntity, data, orderNO);
        /**添加记录*/
        RideCardUser rideCardUser = new RideCardUser();
        rideCardUser.setUserId(user.getUserId());
        rideCardUser.setRideCardId(rideCardId);
        rideCardUser.setAccountId(payPalEntity.getAdAccountId());
        rideCardUser.setStartDate(DateTimeUtil.getNowTimeYMD());
        rideCardUser.setEndDate(DateTimeUtil.getRideCardEndDate(rideCard.getType(),rideCard.getVaildDays()));
        rideCardUser.setOrderNO(data.get("orderNo").toString());

        rideCardUserService.insert(rideCardUser);
        //返回订单号、clientid、支付模式
        map.put(ResponseCode.RET, ResponseCode.SUCC);
        map.put(ResponseCode.DATA, data);
        return map;
    }

    @Override
    public String returnDeposit(User user, WeixinDepositLog weixinDepositLog) {
        //品牌支付配置信息校验
        try {
            long s = System.currentTimeMillis();
            PayPalConfig payPalConfig = checkPayPalConfig(user);
            RefundOrder refundOrder = new RefundOrder();
            Boolean result = refundOrder.refundOrder(payPalConfig.getMode(), payPalConfig.getClientId(), payPalConfig.getClientSecret(), weixinDepositLog.getTransaction_id(), weixinDepositLog.getDepositMoney() / 100, weixinDepositLog.getOut_trade_no());
            LogUtil
                    .info("订单号[" + weixinDepositLog.getOut_trade_no() + "]退款完成用时：" + (System.currentTimeMillis() - s) / 1000 + "秒" + ",结果=" + result);
            if (result) {
                return "ok";
            }
        } catch (Exception e) {
            log.info("订单[" + weixinDepositLog.getOut_trade_no() + "]退款异常：" + e);
            return e.getMessage();
        }
        return null;
    }

    @Override
    public Map<String, Object> createOrder_vipOrder(PayPalEntity payPalEntity, Integer vipId,
                                                    Integer adAccountId) {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> data = new HashMap<String, Object>();
        String orderNO = "UQBIKEVIP" + DateTimeUtil.getDaformatyyyyMMddHHmmss(new Date()) + TenpayUtil.buildRandom(6);
        User user = tokenService.getUser(payPalEntity.getToken());
        /**查询会员卡信息*/
        VipCard vipCard = vipCardService.getById(vipId);
        if (vipCard == null) {
            throw new BaseException("-150002", "会员卡不存在");
        }
        payPalEntity.setUserId(user.getUserId());
        payPalEntity.setMoney(vipCard.getMoney().doubleValue());
        //基础校验
        //baseValid(payPalEntity,data);
    /*String token = getToken(user.getAccountId());
    data.put("accessToken", token);*/
        //基础校验
        baseValid(payPalEntity, data, orderNO);
        //创建订单
        inserOrder(payPalEntity, data, orderNO);

        /**查询是否有购买会员卡*/
        /*VipCardLog vipCardLogDB = vipCardLogService.getById(adAccountId,user.getUserId());

         *//**添加记录*//*
    VipCardLog vipCardLog = new VipCardLog();
    vipCardLog.setVipId(vipId);
    vipCardLog.setAccountId(vipCard.getAccountId());
    vipCardLog.setMemberState(0);
    vipCardLog.setOrderNO(orderNO);
    vipCardLog.setUserId(user.getUserId());
    *//**默认从当天开始计算*//*
    String date = DateTimeUtil.getNowTimeYMD();
    if(vipCardLogDB!=null){
      if(DateTimeUtil.isDepositValid(vipCardLogDB.getExpireDate())){
        date = DateTimeUtil.DateTimeToString(DateTimeUtil.addDay(DateTimeUtil.StringToDateTime(vipCardLogDB.getExpireDate()+" 23:59:59"),1));
      }
    }
    vipCardLog.setExpireDate(DateTimeUtil.getServiceEndDate(date, vipCard.getType()));
    vipCardLog.setEffectDate(date);

    vipCardLogService.add(vipCardLog);*/
        map.put(ResponseCode.RET, ResponseCode.SUCC);
        map.put(ResponseCode.DATA, data);
        return map;
    }


    //基础校验
    private void baseValid(PayPalEntity payPalEntity, Map<String, Object> data, String orderNO) {
        User user = tokenService.getUser(payPalEntity.getToken());
        payPalEntity.setUserId(user.getUserId());
        if (payPalEntity.getDeposit() == null) {
            payPalEntity.setDeposit(false);
        }
        //1.验证充值金额
        if (!payPalEntity.getDeposit() && payPalEntity.getMoney() == null) {
            Assert.notNull(payPalEntity.getMoney(), "-70001", "充值金额不能为空");
        }
        //2.品牌支付配置信息校验
        PayPalConfig config = checkPayPalConfig(user);
        if (config != null) {
            data.put("mode", config.getMode());
        }
        //3.验证用户
        User userDB = userService.getByUserId(user.getUserId());
        if (userDB == null) {
            throw new BaseException("-20005", "用户不存在");
        }
        //4.判断是否是押金退还中
        if (payPalEntity.getDeposit()) {
            if (userDB.getDepositState() == 2) {
                throw new BaseException("-3003", "押金退还中");

            }
        }/*else{
      if(userDB.getDepositState()==0){
        throw new BaseException("-3020","请先提交押金再充值");
      }
    }*/
        //5.如果是押金，获取押金数额
        if (payPalEntity.getDeposit()) {
            payPalEntity.setMoney(getDepositMoney(user, userDB, payPalEntity.getAdAccountId()));
        }
    /*String token = getToken(user.getAccountId());
    data.put("accessToken", token);*/
        /**创建paypal预支付授权订单*/
        String orderId = createOrder(config, payPalEntity.getMoney() / 100, orderNO);
        if (orderId == null) {
            throw new BaseException("-20012", "订单创建失败");
        }
        data.put("orderId", orderId);
    }

    //创建定订单
    private void inserOrder(PayPalEntity payPalEntity, Map<String, Object> data, String orderNO) {
        if (payPalEntity.getDeposit() == null) {
            payPalEntity.setDeposit(false);
        }

        Recharge recharge = new Recharge();
        recharge.setType(RechargeConstant.RECHARGE_PAY_PAL);
        recharge.setRechargeType(payPalEntity.getRechargeType());
        recharge.setOrderNO(orderNO);
        //recharge.setRechargeTime(DateTimeUtil.getNowTime());
        recharge.setRechargeTime(DateTimeUtil.getNowTime());
        recharge.setUserId(payPalEntity.getUserId());
        recharge.setState(0);
        recharge.setMoney(payPalEntity.getMoney());
        recharge.setRemark(payPalEntity.getRemark());
        recharge.setDeposit(payPalEntity.getDeposit());
        rechargeService.insert(recharge);
        data.put("orderNo", orderNO);
        data.put("money", payPalEntity.getMoney() / 100);
        if (payPalEntity.getDeposit()) {

        }
    }

    /**
     * 创建预支付订单
     *
     * @param payPalConfig
     * @param money
     * @param orderNO
     * @return
     */
    public String createOrder(PayPalConfig payPalConfig, Double money, String orderNO) {
        CreateOrder createOrder = new CreateOrder();
        try {
            String orderId = createOrder.createOrder(payPalConfig.getMode(), payPalConfig.getClientId(), payPalConfig.getClientSecret(), "", money, orderNO);
            return orderId;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    private PayPalConfig checkPayPalConfig(User user) {
        PayPalConfig config = payPalConfigDao.findByAccountId(user.getAccountId());
        if (config == null) {
            throw new BaseException("-2011", "该品牌paypal未配置");
        }
        return config;
    }

    private Double getDepositMoney(User userDB, User user, Integer adAccountId) {
        /**是否提交免押*/
        AgentDepositVip agentDepositVip = agentDepositVipService.getByUserId(user.getUserId(), adAccountId);
        if (agentDepositVip != null &&
                DateTimeUtil.getTimeDF(agentDepositVip.getExpireDt() + " 00:00:00", DateTimeUtil.getNowTime()) < 0) {
            throw new BaseException("-120006", "存在生效中的免押卡");
        }
        /**判断平台有没有定义押金*/
        Double money = null;
        AdAccountDeposit adAccountDeposit = adAccountDepositService.getByAccountId(user.getAccountId());
        if (adAccountDeposit == null) {
            adAccountDeposit = adAccountDepositService.getByAccountId(adAccountId);
            if (adAccountDeposit != null) {
                /*判断是否提交押金*/
                if (user.getDepositState() == 1) {
                    /**是否需要补交押金*/
                    if (adAccountDeposit.getDeposit() > user.getDepositMoney()) {
                        money = DoubleUtil.format(adAccountDeposit.getDeposit() - user.getDepositMoney());
                    } else {
                        throw new BaseException("-3009", "押金已经提交");
                    }
                } else if (user.getDepositState() == 0) {
                    money = (double) adAccountDeposit.getDeposit();
                }
            } else {
                throw new BaseException("-3010", "计费规则未定义");
            }
        } else {
            if (user.getDepositState() > 0) {
                throw new BaseException("-3009", "押金已经提交");
            } else {
                money = (double) adAccountDeposit.getDeposit();
            }
        }
        return money;
    }


  /*private Integer updateOrder(HttpServletRequest request,Recharge recharge,User user,String source) {
    //状态：0未支付；1已支付 2：支付中 3：待确认 4:已取消 5支付结果验证失败
    Integer state=recharge.getState();
    if("paypal".equals(source)){//来自paypal的回调
      String paymentStatus=request.getParameter("payment_status");//支付状态  Completed:支付完成
      if(StringUtils.isNotBlank(paymentStatus)) {
        if("completed".equals(paymentStatus.toLowerCase())){//支付完成
          String paymentType=request.getParameter("payment_type");//支付类型 ：instant及时到账
          if("instant".equals(paymentType)) {
            state=1;
          } else {
            state=3;
          }
        }else {
          state=2;
        }
      }else {
        state=2;
      }
      //更新订单状态
      recharge.setState(state);
      recharge.setPayTime(DateTimeUtil.getNowTime());
      rechargeService.update(recharge);
      //更新订单状态并绑定用户租车或充值信息
      updateOrderAndBing(recharge,user,request.getParameter("paymentId"));
    }else if("app".equals(source)){//来自app的回调
      LogUtil.info("订单："+recharge.getOrderNO()+"原状态："+recharge.getState());
      //时序图第6步-验证支付结果有效性
      state=validPayResult(request,source,recharge,user);
      recharge.setState(state);
      recharge.setPayTime(DateTimeUtil.getNowTime());
      LogUtil.info("订单："+recharge.getOrderNO()+"新状态："+recharge.getState());
      rechargeService.update(recharge);
    }
    return state;
  }*/

    //记录押金充值日志，用于日后押金退还
    private void insertPayPalLog(User user, Recharge recharge, String transId) {
        WeixinDepositLog weixinDepositLog = weixinDepositLogService.getByOrderNo(recharge.getOrderNO());
        if (weixinDepositLog == null) {
            weixinDepositLog = new WeixinDepositLog();
            weixinDepositLog.setAccountId(user.getAccountId());
            weixinDepositLog.setType(recharge.getType());
            weixinDepositLog.setUserId(user.getUserId());
            weixinDepositLog.setDepositMoney(recharge.getMoney());
            weixinDepositLog.setAddTime(DateTimeUtil.getNowTime());
            weixinDepositLog.setOut_trade_no(recharge.getOrderNO());
            weixinDepositLog.setTransaction_id(transId);
            weixinDepositLog.setRemark("用户提交的押金");
            weixinDepositLogService.insert(weixinDepositLog);
        } else {
            weixinDepositLog.setDepositMoney(recharge.getMoney());
            weixinDepositLog.setTransaction_id(transId);
            weixinDepositLogService.update(weixinDepositLog);
        }
    }


    //调用paypal接口查询订单详情校验支付结果有效性
  /*private Integer validPayResult(HttpServletRequest request,String source,Recharge recharge,User user) {
    Integer state=recharge.getState();
    String orderNo=request.getParameter("custom");//订单号
    String paymentId=null;
    if("app".equals(source)) {//app回调
      String paymentStatus=request.getParameter("state");
      log.info("订单来源:"+source+",订单号："+orderNo+",paymentStatus:"+paymentStatus);
      if("cancel".equals(paymentStatus)){//用户手动取消支付
        state=4;
      }else{//支付成功回调
        //app回调服务器-返回支付流水号和支付结果
        paymentId=request.getParameter("paymentId");
        log.info("支付流水号paymemntId:"+paymentId+"订单当前状态："+state);
        if(StringUtils.isNotBlank(paymentId)){
          if("approved".equals(paymentStatus)) {
            if(state==1) {//paypal已回调
              weixinDepositLogService.updateTransNo(orderNo, paymentId);
              log.info("订单号:"+orderNo+"修改weixinDepositLog交易流水："+paymentId);
            }else{//app优先于paypal回调
              log.info("app优先于paypal回调订单号:"+orderNo+",交易流水："+paymentId);
              //调用paypal查询接口验证支付有效性
              //state=validPayStateByPayPal(recharge,user,paymentId);
              recharge.setState(state);
              //String route_key=CommonUtil.getOrderRedisKey(orderNo);
              // redisService.add(route_key, paymentId, 90*24*3600);//90天失效
              //state=3;//待确认
            }
          }
        }
        log.info("支付流水号paymemntId:"+paymentId+"订单处理后状态："+state);
      }
      editPayDetail(orderNo,paymentId,state,paymentStatus);
      return state;
    }
    return state;
  }*/




  /*private void editPayDetail(String orderNo,String paymentId,Integer state,String paymentStatus) {
    synchronized (orderNo) {
      PayDetail pd=payDetailDao.getByOrderNo(orderNo);
      PayDetail pdNew=new PayDetail();
      pdNew.setPaymentId(paymentId);
      pdNew.setState(state);
      pdNew.setOrderNo(orderNo);
      pdNew.setAppState(paymentStatus);
      pdNew.setUpdateTime(DateTimeUtil.getNowTime());
      //更新付款详情
      if(pd!=null) {
        pdNew.setRemark(pd.getRemark()+";app回调结果["+state+"]");
        payDetailDao.update(pdNew);
        log.info("app回调更新["+orderNo+"]付款详情PayDetail："+ JSONObject.toJSONString(pdNew));
      }else {
        pdNew.setRemark("app回调结果["+state+"]");
        payDetailDao.insert(pdNew);
        log.info("app回调新增["+orderNo+"]付款详情PayDetail："+JSONObject.toJSONString(pdNew));
      }
    }
  }*/

    //修改骑行日志
 /* private void updateRideLog(User user,Recharge recharge) {
    if(user.getMoney()<0&&(user.getMoney()+recharge.getMoney()>=0)){
      log.info("paypal更新用户["+user.getPhone()+"]最后一笔骑行日志中的支付时间");
      try{
        //先查询
        RideLog rideLog=rideLogService.findLastByUserId(user.getUserId());
        if(rideLog!=null){
          rideLogService.updatePayTimeByUserIdAndOrderNO(user.getUserId(),new Date(),rideLog.getOrderNO());
        }
      }catch(Exception e){
        log.info("paypal更新rideLog错误"+e.getMessage(),e);
      }

    }
  }*/


}
